use std::f32::INFINITY;

pub struct ProgressBar {
    title: String,
    display_index: i32,
    progress: f32,
    display_content: String,
}

impl ProgressBar {
    pub fn new() -> Self {
        Self {
            title: String::from(""),
            display_index: 0,
            progress: 0.0,
            display_content: String::from(""),
        }
    }
    pub fn set_title(&mut self, title: &str) {
        self.title = String::from(title);
    }
    pub fn set_progress(&mut self, progress: f32) {
        self.progress = progress;
    }
    fn clear(&mut self) {
        print!("\r");
    }
    pub fn display(&mut self) {
        self.display_with_extra("");
    }
    pub fn display_with_extra(&mut self, extra: &str) {
        self.clear();
        let mut active = String::new();
        self.display_index = (30.0 * (self.progress / 100.0)).floor() as i32;
        for i in 0..31 {
            if i == self.display_index {
                if self.display_index == 30 {
                    active.push(' ');
                } else {
                    active.push('>');
                }
            } else if i > 0 && i < self.display_index {
                active.push('=');
            } else {
                active.push(' ');
            }
        }
        let progress_tips = if self.progress == INFINITY {
            String::from("--")
        } else {
            format!("{:.2}", self.progress)
        };

        if extra.is_empty() {
            self.display_content = format!("{:8} [{}] {}%", self.title, active, progress_tips);
        } else {
            self.display_content =
                format!("{:8} [{}] {} {}%", self.title, active, extra, progress_tips);
        }
        print!("{}", self.display_content);
    }
}
